//
//  Extension+NSAttributedString.swift
//  SHWeibo
//
//  Created by jingming wang on 16/8/1.
//  Copyright © 2016年 cpy.name. All rights reserved.
//

import UIKit

extension NSAttributedString {
    
    class func stringWithFormat(string: String?, fromSubstring: String, toSubsting: String, defaultString: String?, prefix: String?)-> NSAttributedString{
        // 判断是否为nil 而且是否保存">
        
        guard let s = string where s.containsString(fromSubstring) else{
            return setAttr(defaultString ?? "", prefix: prefix)
        }
        // 起始位置和结束位置
        let startRange = s.rangeOfString(fromSubstring)!
        let endRange = s.rangeOfString(toSubsting)!
        
        // 字符串截取
        let result = s.substringWithRange(startRange.endIndex..<endRange.startIndex)
        return setAttr(result, prefix: prefix)
    }
    // 处理显示微博来源的富文本
    class func setAttr(result: String, prefix:String?) -> NSAttributedString {
        // 判断是否为nil
        guard let _ = prefix else {
            return NSMutableAttributedString(string: result)
        }
        // 最终显示格式
        let name = prefix! + result
        // 得到range
        let range = (name as NSString).rangeOfString(prefix!)
        
        // 创建一个可变富文本
        let attr = NSMutableAttributedString(string: name)
        // 设置属性
        attr.addAttributes([NSForegroundColorAttributeName: UIColor.grayColor()], range: range)
        
        return attr as NSAttributedString
    }
    
    // 遍历构造函数
    convenience init(emoticon: SHEmoticon, y: CGFloat, lineHeight: CGFloat) {
        // 文本附件
        let att = SHTextAttachment()
        // 赋值
        att.emoticon = emoticon
        // 设置image
        att.image = UIImage.getEmoticonImage(emoticon.path)
        // 记住一定要设置bounds
        att.bounds = CGRect(x: 0, y: y, width: lineHeight, height: lineHeight)
        self.init(attachment: att)
    }

    
}

